
/**
 * @file ReadRinexIndexFile.cpp
 * This class synchronizes rinex observation data streams.
 */

#include "ReadRinexIndexFile.hpp"

using namespace std;
using namespace gpstk;
using namespace StringUtils;

#define debug 0

namespace gpstk
{
      // Add a rinex obs file to the network
      // @obsFile   Rinex observation file name
    bool ReadRinexIndexFile::addRinexObsFile(const std::string& obsFile)
    {

        try
        {
            Rinex3ObsStream rinexStream;

            // open the obs file
            rinexStream.exceptions(std::ios::failbit);
            rinexStream.open(obsFile, std::ios::in);

            // read the header of the obs file
            Rinex3ObsHeader obsHeader;
            rinexStream >> obsHeader;

            SourceID source;

            source.type = SatIDsystem2SourceIDtype(obsHeader.fileSysSat);
            source.sourceName = StringUtils::upperCase( obsHeader.markerName.substr(0,4));

            sourceRinexFileData[source] = obsFile;

            return true;
        }
        catch(...)
        {
            // Problem opening the file
            return false;
        }

    }  // End of method 'ReadRinexIndexFile::addRinexObsFile()'


      // Add a rinex obs file to the network
      // @obsFile   Rinex observation file name
    bool ReadRinexIndexFile::setRinexIndexFile(const std::string& rnxIndexFile)
    {

        ifstream inpf(rnxIndexFile.c_str());
        if(!inpf)
        {
           FileMissingException fme("Could not open rinex index file " + rnxIndexFile);
           GPSTK_THROW(fme);
        }

           // Now, read the leap second data
        bool ok (true);
        while(!inpf.eof() && inpf.good())
        {
           string line;
           getline(inpf,line);
           StringUtils::stripTrailing(line,'\r');

           if( inpf.eof() ) break;
           if( inpf.bad() ) break;

           if(debug)
           {
              cout << "line:" << line << endl;
           }

              // Now, let's add this rinex file into 'network streams'
           addRinexObsFile(line);

        }

        inpf.close();

        return true;

        if(!ok)
        {
           FileMissingException fme("rinex index File " + rnxIndexFile
                                    + " is corrupted or wrong format");
           GPSTK_THROW(fme);

           return false;
        }
    }  // End of method 'ReadRinexIndexFile::setRinexIndexFile()'

}  // End of namespace gpstk
